<template>
  <ElForm :model="user">
    <ElFormItem>
      <ElInput :prefix-icon="Iphone" v-model="user.phone" placeholder="请输入手机号" style="width: 310px;"/>
    </ElFormItem>
    <ElFormItem>
      <ElRow :gutter="20">
        <ElCol :span="15">
          <ElInput v-model="user.verificationCode" placeholder="请输入验证码" />
        </ElCol>
        <ElCol :span="9">
          <ElButton @click="getVerificationCode" :disabled="countdown > 0" style="font-weight: bold;">
            {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
          </ElButton>
        </ElCol>
      </ElRow>
    </ElFormItem>
    <ElFormItem>
      <ElButton  size="large" style="width: 100%;margin-top: 40px;background-color: #0460FF;color: #FFF;" @click="login">登录</ElButton>
    </ElFormItem>
  </ElForm>
</template>

<script setup>
import { ref } from 'vue'
import {Iphone} from "@element-plus/icons-vue";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";

const countdown = ref(0)

const user = ref({
  phone: '',
  verificationCode: '',
})

const getVerificationCode = () => {
  if (countdown.value > 0) return;
  axios.post(getBaseURL(4) + '/v1/sms/send/'+user.value.phone)
      .then(response => {
        if (response.data.code){
          ElMessage.success('验证码发送成功')
          countdown.value = 60;
          const timer = setInterval(() => {
            countdown.value--;
            if (countdown.value <= 0) {
              clearInterval(timer);
            }
          }, 1000);
        }else{
          ElMessage.error(response.data.msg)
          user.value.verificationCode = ''
        }
      })
      .catch(error => {
        ElMessage.error(error.message)
        console.log(error)
      })
}

const login = () => {
  user.value.loginType = 'phone';
  axios.post(getBaseURL(4) + '/v1/user/login',qs.stringify(user.value))
      .then(response => {
        if (response.data.code === 2000){
          ElMessage.success('登录成功')
          localStorage.setItem('user',JSON.stringify(response.data))
          router.push('/')
        }else{
          ElMessage.error(response.data.msg)
          user.value.verificationCode = ''
        }
      })
      .catch(error => {
        ElMessage.error(error.message)
        console.log(error)
      })
}
</script>
